package org.leiyang.repository;

import org.leiyang.common.entities.MsgOneToOne;
import org.springframework.data.r2dbc.repository.Modifying;
import org.springframework.data.r2dbc.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

public interface MsgOneToOneRepository extends ReactiveCrudRepository<MsgOneToOne, Long> {

    /**
     * 批量更新{@link MsgOneToOne#send}
     * @param msgIds 逗号分隔的字符串
     */
    @Modifying
    @Query("UPDATE msg_one_to_one SET send = 1 where id in (:msgIds)")
    Mono<Integer> batchUpdateMsgOneToOneReceive(@Param("msgIds") List<String> msgIds);

    /**
     * 新增msg
     */
    @Modifying
    @Query("insert into msg_one_to_one values (:id,:fromUserId,:toUserId,:msgType,:textMsg,:avMsgUrl,:imgWidth,:imgHeight,:send,:time)")
    Mono<Long> addNewMsg(@Param("id") Long id, @Param("fromUserId") Long fromUserId, @Param("toUserId") Long toUserId, @Param("msgType") Integer msgType,
                         @Param("textMsg") String textMsg, @Param("avMsgUrl") String avMsgUrl, @Param("imgWidth") Integer imgWidth, @Param("imgHeight") Integer imgHeight,
                         @Param("send") Integer send, @Param("time") Long time);

    /**
     * 获取用户A与用户B的聊天记录(不包括未接收状态的消息)
     * 待改为分页方式查询
     * @param currentUid 当前用户ID
     * @param toUid 对方用户ID
     * @return 聊天记录
     */
    @Query("SELECT * FROM msg_one_to_one WHERE ((fromUserId = :currentUid and toUserId = :toUid) or (fromUserId = :toUid and toUserId = :currentUid and send = 1))")
    Flux<MsgOneToOne> listAllHistoryMsgs(@Param("currentUid") Long currentUid, @Param("toUid") Long toUid);

}
